package com.next.aappublicapp;

import java.util.ArrayList;
import java.util.List;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.UserDictionary;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.model.GraphUser;
import com.facebook.widget.ProfilePictureView;
import com.google.analytics.tracking.android.EasyTracker;
import com.next.aap.client.AssemblyConstituencyDto;
import com.next.aap.client.DistrictDto;
import com.next.aap.client.RegisterFacebookUserProfile;
import com.next.aap.client.StateDto;
import com.next.aappublicapp.adapters.AssemblyConstituencySpinnerAdapter;
import com.next.aappublicapp.adapters.DistrictSpinnerAdapter;
import com.next.aappublicapp.adapters.StateSpinnerAdapter;
import com.next.aappublicapp.server.service.DataServices;
import com.next.aappublicapp.tasks.AapAsyncTask;
import com.next.aappublicapp.util.FacebookUtil;
import com.next.aappublicapp.util.GcmUtil;
import com.next.aappublicapp.util.UserProfileUtil;

public class UserProfileActivity extends BaseActivity {

	private ProfilePictureView profilePictureView;
	private EditText userNameEditText;
	private EditText userEmailEditText;
	private EditText userMobileEditText;
	private Spinner emailSpinner;
	private TextView emailSpinnerTextView;
	private Spinner stateSpinner;
	private Spinner userLivingDistrictSpinner;
	private Spinner userLivingAcSpinner;
	private Spinner stateVoterSpinner;
	private Spinner userVoterDistrictSpinner;
	private Spinner userVoterAcSpinner;
	private String otherEmailId = "Other";
	private Button saveAndConttinueButton;
	private Button skipAndConttinueButton;
	private GraphUser user;
	private LinearLayout profileStatus;
	private LinearLayout profileView;

	private LinearLayout userLivingDistrictLinearLayout;
	private LinearLayout userLivingAcLinearLayout;
	private LinearLayout userVoterDistrictLinearLayout;
	private LinearLayout userVoterAcLinearLayout;

	private ProgressBar userLivingLocationProgressBar;
	private ProgressBar userVotingLocationProgressBar;
	
	private long selectedLivingStateId = -1l;
	private long selectedVotingStateId = -1l;

	private long selectedLivingDistrictId = -1l;
	private long selectedVotingDistrictId = -1l;

	private long selectedLivingAcId = -1l;
	private long selectedVotingAcId = -1l;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_profile);
		EasyTracker.getTracker().sendView("Save Profile Screen");

		profilePictureView = (ProfilePictureView) findViewById(R.id.selection_profile_pic);
		profilePictureView.setCropped(true);

		userLivingLocationProgressBar = (ProgressBar) findViewById(R.id.userLivingLocationProgressBar);
		userLivingLocationProgressBar.setVisibility(View.GONE);
		userVotingLocationProgressBar = (ProgressBar) findViewById(R.id.userVotingLocationProgressBar);
		userVotingLocationProgressBar.setVisibility(View.GONE);
		
		

		userLivingDistrictLinearLayout = (LinearLayout) findViewById(R.id.userLivingDistrictLinearLayout);
		userLivingAcLinearLayout = (LinearLayout) findViewById(R.id.userLivingAcLinearLayout);
		userVoterDistrictLinearLayout = (LinearLayout) findViewById(R.id.userVoterDistrictLinearLayout);
		userVoterAcLinearLayout = (LinearLayout) findViewById(R.id.userVoterAcLinearLayout);

		// Find the user's name view
		profileStatus = (LinearLayout) findViewById(R.id.profile_status);
		profileView = (LinearLayout) findViewById(R.id.profile_view);

		userNameEditText = (EditText) findViewById(R.id.userName);
		userEmailEditText = (EditText) findViewById(R.id.userEmail);
		userEmailEditText.setVisibility(View.GONE);
		userMobileEditText = (EditText) findViewById(R.id.userMobile);
		emailSpinner = (Spinner) findViewById(R.id.email_spinner);
		emailSpinnerTextView = (TextView) findViewById(R.id.email_spinner_text_view);
		stateSpinner = (Spinner) findViewById(R.id.state_spinner);
		userLivingDistrictSpinner = (Spinner) findViewById(R.id.user_living_district_spinner);
		userLivingAcSpinner = (Spinner) findViewById(R.id.user_living_ac_spinner);
		stateVoterSpinner = (Spinner) findViewById(R.id.state_voter_spinner);
		userVoterDistrictSpinner = (Spinner) findViewById(R.id.user_voter_district_spinner);
		userVoterAcSpinner = (Spinner) findViewById(R.id.user_voter_ac_spinner);
		
		// populateStateList();
		loadStateListAsync();
		saveAndConttinueButton = (Button) findViewById(R.id.save_and_continue);
		skipAndConttinueButton = (Button) findViewById(R.id.skip_and_continue);

		makeMeRequest(Session.getActiveSession());
		skipAndConttinueButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				EasyTracker.getTracker().sendEvent("Android", "SaveProfile",
						"SkipProfileSaving", 1L);
				startMainActivty();
			}
		});

		saveAndConttinueButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				EasyTracker.getTracker().sendEvent("Android", "SaveProfile",
						"SaveProfile", 1L);
				boolean hasErrors = false;

				AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
						UserProfileActivity.this);
				// set title
				alertDialogBuilder.setTitle("Errors");

				userEmailEditText.setError(null);
				userMobileEditText.setError(null);
				emailSpinnerTextView.setError(null);
				String errorMesage = "";
				RegisterFacebookUserProfile registerFacebookUserProfile = new RegisterFacebookUserProfile();
				registerFacebookUserProfile.setName(userNameEditText.getText()
						.toString());
				if (emailSpinner.getSelectedItem().equals(otherEmailId)) {
					registerFacebookUserProfile.setEmail(userEmailEditText
							.getText().toString());
				} else {
					registerFacebookUserProfile.setEmail(emailSpinner
							.getSelectedItem().toString());
				}
				registerFacebookUserProfile.setMobile(userMobileEditText
						.getText().toString());
				registerFacebookUserProfile.setVotingState(null);
				if (stateVoterSpinner.getSelectedItemPosition() <= 0) {
					errorMesage = errorMesage + "Select a voter State\n";
					hasErrors = true;
				} else {
					registerFacebookUserProfile.setVotingStateId(((StateDto)stateVoterSpinner.getSelectedItem()).getId());
				}
				if (userVoterDistrictSpinner.getSelectedItemPosition() <= 0) {
				} else {
					registerFacebookUserProfile.setVotingDistrictId(((DistrictDto)userVoterDistrictSpinner.getSelectedItem()).getId());
				}
				if (userVoterAcSpinner.getSelectedItemPosition() <= 0) {
				} else {
					registerFacebookUserProfile.setVotingAcId(((AssemblyConstituencyDto)userVoterAcSpinner.getSelectedItem()).getId());
				}

				if (stateSpinner.getSelectedItemPosition() <= 0) {
					errorMesage = errorMesage + "Select a Living State\n";
					registerFacebookUserProfile.setLivingState(null);
				} else {
					registerFacebookUserProfile.setLivingStateId(((StateDto)stateSpinner.getSelectedItem()).getId());
				}
				if (userLivingDistrictSpinner.getSelectedItemPosition() <= 0) {
				} else {
					registerFacebookUserProfile.setLivingDistrictId(((DistrictDto)userLivingDistrictSpinner.getSelectedItem()).getId());
				}
				if (userLivingAcSpinner.getSelectedItemPosition() <= 0) {
				} else {
					registerFacebookUserProfile.setLivingAcId(((AssemblyConstituencyDto)userLivingAcSpinner.getSelectedItem()).getId());
				}
				registerFacebookUserProfile.setUserName(user.getUsername());
				registerFacebookUserProfile.setAccessToken(Session
						.getActiveSession().getAccessToken());
				registerFacebookUserProfile.setBirthday(user.getBirthday());
				registerFacebookUserProfile.setDeviceRegId(GcmUtil
						.getGcmDeviceRegistrationId(UserProfileActivity.this));
				registerFacebookUserProfile.setGender((String) user
						.getProperty("gender"));
				Log.i("Ravi",
						"setDeviceRegId="
								+ registerFacebookUserProfile.getDeviceRegId());
				Log.i("Ravi", "user.getUsername()=" + user.getUsername());
				Log.i("Ravi", "user.getBirthday()=" + user.getBirthday());
				Log.i("Ravi", "user.getId()=" + user.getId());
				Log.i("Ravi",
						"user.gender()=" + (String) user.getProperty("gender"));
				Log.i("Ravi",
						"user.gender()="
								+ (String) user.getProperty("birthday"));
				if (registerFacebookUserProfile.getUserName() == null) {
					registerFacebookUserProfile.setUserName((String) user
							.getProperty("email"));
				}
				if (registerFacebookUserProfile.getEmail() == null
						|| registerFacebookUserProfile.getEmail().trim()
								.isEmpty()) {
					errorMesage = errorMesage
							+ "Please Enter a valid email Id\n";
					hasErrors = true;
					// userEmailEditText.setError("Please Enter a valid email Id");
					// emailSpinnerTextView.setError("Please Enter a valid email Id");
				}
				if (registerFacebookUserProfile.getMobile() == null
						|| registerFacebookUserProfile.getMobile().trim()
								.isEmpty()
						|| registerFacebookUserProfile.getMobile().trim()
								.length() != 10) {
					hasErrors = true;
					// userMobileEditText.setError("Please Enter a valid Mobile number of 10 digits");
					errorMesage = errorMesage
							+ "Please Enter a valid Mobile no.\n";
				}
				alertDialogBuilder.setMessage(errorMesage);

				if (!hasErrors) {
					UserProfileUtil.saveUserProfile(UserProfileActivity.this,
							registerFacebookUserProfile);

					// and now move to next screen without worrying about result
					// of registration
					startMainActivty();
				} else {
					alertDialogBuilder.setPositiveButton("Ok",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									// if this button is clicked, close
									// current activity
									// UserProfileActivity.this.finish();
									dialog.dismiss();
								}
							});
					// create alert dialog
					AlertDialog alertDialog = alertDialogBuilder.create();

					// show it
					alertDialog.show();
				}
			}
		});

		stateSpinner
				.setOnItemSelectedListener(new LivingStateOnItemSelectedListener());
		stateVoterSpinner
				.setOnItemSelectedListener(new VotingStateOnItemSelectedListener());
		userLivingDistrictSpinner.setOnItemSelectedListener(new LivingDistrictOnItemSelectedListener());
		userVoterDistrictSpinner.setOnItemSelectedListener(new VotingDistrictOnItemSelectedListener());
		
	}
	private void selectState(long stateId,Spinner paramStateSpinner){
		if(stateId > 0){
			StateSpinnerAdapter stateSpinnerAdapter = (StateSpinnerAdapter)paramStateSpinner.getAdapter();
			if(stateSpinnerAdapter != null){
				StateDto stateDto; 
				for(int i=0;i<stateSpinnerAdapter.getCount();i++){
					stateDto = stateSpinnerAdapter.getItem(i);
					if(stateDto.getId().equals(stateId)){
						paramStateSpinner.setSelection(i);
						break;
					}
				}
			}
		}
	}
	private void selectDistrict(long districtId,Spinner paramDistrictSpinner){
		if(districtId > 0){
			DistrictSpinnerAdapter districtSpinnerAdapter = (DistrictSpinnerAdapter)paramDistrictSpinner.getAdapter();
			if(districtSpinnerAdapter != null){
				DistrictDto districtDto; 
				for(int i=0;i<districtSpinnerAdapter.getCount();i++){
					districtDto = districtSpinnerAdapter.getItem(i);
					if(districtDto.getId().equals(districtId)){
						paramDistrictSpinner.setSelection(i);
						break;
					}
				}
			}
		}
	}
	private void selectAssemblyContituency(long assemblyConstituencyId,Spinner paramAcSpinner){
		if(assemblyConstituencyId > 0){
			AssemblyConstituencySpinnerAdapter districtSpinnerAdapter = (AssemblyConstituencySpinnerAdapter)paramAcSpinner.getAdapter();
			if(districtSpinnerAdapter != null){
				AssemblyConstituencyDto assemblyConstituencyDto; 
				for(int i=0;i<districtSpinnerAdapter.getCount();i++){
					assemblyConstituencyDto = districtSpinnerAdapter.getItem(i);
					if(assemblyConstituencyDto.getId().equals(assemblyConstituencyId)){
						paramAcSpinner.setSelection(i);
						break;
					}
				}
			}
		}
	}
	private void populateUserProfile(){
		RegisterFacebookUserProfile registerFacebookUserProfile =  UserProfileUtil.getUserProfile(UserProfileActivity.this);
		Log.i("RegisterFacebookUserProfile", "registerFacebookUserProfile="+registerFacebookUserProfile);
		if(registerFacebookUserProfile != null){
			userNameEditText.setText(registerFacebookUserProfile.getName());
			
			userMobileEditText.setText(registerFacebookUserProfile.getMobile());
			//Save in class variable, it may be possible states have not been loaded by now and need to select again
			selectedLivingStateId = registerFacebookUserProfile.getLivingStateId();
			selectedVotingStateId = registerFacebookUserProfile.getVotingStateId();
			//Put rest of values in 
			selectedLivingDistrictId = registerFacebookUserProfile.getLivingDistrictId();
			selectedVotingDistrictId = registerFacebookUserProfile.getVotingDistrictId();
			
			selectedLivingAcId = registerFacebookUserProfile.getLivingAcId();
			selectedVotingAcId = registerFacebookUserProfile.getVotingAcId();
			
			
			selectState(registerFacebookUserProfile.getLivingStateId(),stateSpinner);
			selectState(registerFacebookUserProfile.getVotingStateId(),stateVoterSpinner);
			
		}
	}

	private void populateStateList() {
		List<String> stateList = new ArrayList<String>();
		stateList.add("Select a State");
		stateList.add("Andaman and Nicobar Islands(UT)");
		stateList.add("Andhra Pradesh");
		stateList.add("Arunachal Pradesh");
		stateList.add("Assam");
		stateList.add("Bihar");
		stateList.add("Chandigarh(UT)");
		stateList.add("Chhattisgarh");
		stateList.add("Dadra and Nagar Haveli(UT)");
		stateList.add("Daman and Diu(UT)");
		stateList.add("Delhi");
		stateList.add("Goa");
		stateList.add("Gujarat");
		stateList.add("Haryana");
		stateList.add("Himachal Pradesh");
		stateList.add("Jammu and Kashmir");
		stateList.add("Jharkhand");
		stateList.add("Karnataka");
		stateList.add("Kerala");
		stateList.add("Lakshadweep(UT)");
		stateList.add("Madhya Pradesh");
		stateList.add("Maharashtra");
		stateList.add("Manipur");
		stateList.add("Meghalaya");
		stateList.add("Mizoram");
		stateList.add("Nagaland");
		stateList.add("Odisha");
		stateList.add("Puducherry");
		stateList.add("Punjab");
		stateList.add("Rajasthan");
		stateList.add("Sikkim");
		stateList.add("Tamil Nadu");
		stateList.add("Tripura");
		stateList.add("Uttar Pradesh");
		stateList.add("Uttarakhand");
		stateList.add("West Bengal");

		List<String> livingStateList = new ArrayList<String>(stateList);

		livingStateList.add(1, "Outside India/NRI/PIO etc");

		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, livingStateList);
		dataAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		stateSpinner.setAdapter(dataAdapter);
		stateSpinner
				.setOnItemSelectedListener(new LivingStateOnItemSelectedListener());

		ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, stateList);
		dataAdapter2
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		stateVoterSpinner.setAdapter(dataAdapter2);
		// stateVoterSpinner.setOnItemSelectedListener(new
		// CustomOnItemSelectedListener());

	}

	private void startMainActivty() {
		Log.i("Ravi", "Main Activity Starting");
		// makeMeRequest(Session.getActiveSession());
		Intent intent = new Intent(this, MainActivity.class);
		Bundle bundle = new Bundle();
		intent.putExtra(PagerViewActivity.ARGS_BUNDLE, bundle);
		this.startActivity(intent);
		finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.user_profile, menu);
		return true;
	}

	private void makeMeRequest(final Session session) {
		// Make an API call to get user data and define a
		// new callback to handle the response.
		List<String> permissionsRequired = new ArrayList<String>();
		permissionsRequired.add("email");
		permissionsRequired.add("user_birthday");

		// permissionsRequired.add("username");
		// permissionsRequired.add("gender");
		// permissionsRequired.add("birthday");
		// permissionsRequired.add("user_mobile_phone");
		// permissionsRequired.add("user_address");
		profileStatus.setVisibility(View.VISIBLE);
		profileView.setVisibility(View.GONE);
		FacebookUtil.checkReadPermission(this, permissionsRequired);
		Request request = Request.newMeRequest(session,
				new Request.GraphUserCallback() {
					@Override
					public void onCompleted(GraphUser user, Response response) {
						try {
							//Log.i("Ravi", "GraphUser=" + user);
							//Log.i("Ravi", "response=" + response);
							//Log.i("Ravi", "Session.getActiveSession()="+ Session.getActiveSession());
							// If the response is successful
							if (session == Session.getActiveSession()) {
								if (user != null) {
									FacebookUtil.saveFaceookUserId(
											UserProfileActivity.this,
											user.getId());
									FacebookUtil.saveFaceookUser(
											UserProfileActivity.this, user);
									UserProfileActivity.this.user = user;
									// Set the id for the ProfilePictureView
									// view that in turn displays the profile
									// picture.
									profilePictureView.setProfileId(user
											.getId());
									// Set the Textview's text to the user's
									// name.
									userNameEditText.setText(user.getName());
									String facebookEmail = (String) user
											.getProperty("email");
									List<String> emails = getEmail(UserProfileActivity.this);
									if (!emails.contains(facebookEmail)) {
										emails.add(facebookEmail);
									}
									emails.add(otherEmailId);
									addItemsOnEmailSpinner(emails);
									// userMobileEditText.setText((String)
									// user.getProperty("user_mobile_phone"));
									userMobileEditText
											.setText(getMyPhoneNumber());
									// userEmailEditText.setText(user.get)
									userMobileEditText
											.setFocusableInTouchMode(true);
									userMobileEditText.setFocusable(true);
									userMobileEditText.requestFocus();
									
									populateUserProfile();

								}
							}
							if (response.getError() != null) {
								// Handle errors, will do so later.
							}
						} finally {
							profileStatus.setVisibility(View.GONE);
							profileView.setVisibility(View.VISIBLE);

						}

					}
				});
		request.executeAsync();
	}

	private List<String> getEmail(Context context) {
		AccountManager accountManager = AccountManager.get(context);
		Account[] accounts = accountManager.getAccountsByType("com.google");
		List<String> emailIds = new ArrayList<String>();
		if (accounts.length > 0) {
			for (Account oneAccount : accounts) {
				emailIds.add(oneAccount.name);
			}
		}
		return emailIds;
	}

	private String getMyPhoneNumber() {
		TelephonyManager mTelephonyMgr;
		mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		Log.i("Ravi",
				"mTelephonyMgr.getLine1Number()="
						+ mTelephonyMgr.getLine1Number());
		Log.i("Ravi",
				"mTelephonyMgr.getVoiceMailNumber()="
						+ mTelephonyMgr.getVoiceMailNumber());
		return mTelephonyMgr.getLine1Number();
	}

	public void addItemsOnEmailSpinner(List<String> emails) {

		ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, emails);
		dataAdapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		emailSpinner.setAdapter(dataAdapter);
		emailSpinner
				.setOnItemSelectedListener(new CustomOnItemSelectedListener());
	}

	public class CustomOnItemSelectedListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			if (otherEmailId.equals(parent.getItemAtPosition(pos).toString())) {
				userEmailEditText.setVisibility(View.VISIBLE);

				userEmailEditText.setFocusableInTouchMode(true);
				userEmailEditText.setFocusable(true);
				userEmailEditText.requestFocus();

			} else {
				userEmailEditText.setVisibility(View.GONE);
				userMobileEditText.setFocusableInTouchMode(true);
				userMobileEditText.setFocusable(true);
				userMobileEditText.requestFocus();
			}
			/*
			 * Toast.makeText(parent.getContext(), "OnItemSelectedListener : " +
			 * parent.getItemAtPosition(pos).toString(),
			 * Toast.LENGTH_SHORT).show();
			 */
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}

	}

	private List<StateDto> allStates = null;

	private void loadStateListAsync() {
		Log.i("Ravi", "Loading States "+allStates);
		if (allStates == null) {
			new AapAsyncTask<String, String, List<StateDto>>("state", "getall") {
				@Override
				protected List<StateDto> doInBackground(String... params) {
					try {
						Log.i("Ravi", "Loading States");
						List<StateDto> states = DataServices.getInstance().getAllStates();
						Log.i("Ravi", "Loaded States");
						return states;
					} catch (Exception ex) {
						Log.e("Ravi", "Error while Loading States",ex);
					}
					return null;
				}

				@Override
				protected void afterExecute(List<StateDto> result) {
					Log.i("Ravi", "Loaded  States " + result);
					if (result != null) {
						allStates = result;

						StateDto selecteState = new StateDto();
						selecteState.setId(-1L);
						selecteState.setName("--Select State---");
						result = new ArrayList<StateDto>(result);
						result.add(0, selecteState);
						stateSpinner.setAdapter(new StateSpinnerAdapter(
								UserProfileActivity.this,
								android.R.layout.simple_spinner_item, result));
						stateVoterSpinner.setAdapter(new StateSpinnerAdapter(
								UserProfileActivity.this,
								android.R.layout.simple_spinner_item, result));
						selectState(selectedLivingStateId,stateSpinner);
						selectState(selectedVotingStateId,stateVoterSpinner);

					}
				}
			}.execute();
		}

	}

	public class LivingStateOnItemSelectedListener implements
			OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			if (pos == 0) {
				userLivingAcLinearLayout.setVisibility(View.GONE);
				userLivingDistrictLinearLayout.setVisibility(View.GONE);
			} else {
				
				StateDto selectedState = (StateDto) parent
						.getItemAtPosition(pos);
				if(selectedState.getDistrictDataAvailable() != null && selectedState.getDistrictDataAvailable()){
					loadDistrictOfStateAsync(userLivingDistrictSpinner,
							userLivingLocationProgressBar,
							userLivingDistrictLinearLayout, selectedState.getId());
				}else{
					userLivingAcLinearLayout.setVisibility(View.GONE);
					userLivingDistrictLinearLayout.setVisibility(View.GONE);
				}
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}

	}

	public class LivingDistrictOnItemSelectedListener implements
			OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			if (pos == 0) {
				userLivingAcLinearLayout.setVisibility(View.GONE);
			} else {
				DistrictDto districtDto = (DistrictDto) parent
						.getItemAtPosition(pos);
				if(districtDto.getAcDataAvailable() != null && districtDto.getAcDataAvailable()){
					loadAcOfDistrictAsync(userLivingAcSpinner,
							userLivingLocationProgressBar,
							userLivingAcLinearLayout, districtDto.getId());
				}else{
					userLivingAcLinearLayout.setVisibility(View.GONE);
				}
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}

	}

	public class VotingStateOnItemSelectedListener implements
			OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			if (pos == 0) {
				userVoterAcLinearLayout.setVisibility(View.GONE);
				userVoterDistrictLinearLayout.setVisibility(View.GONE);
			} else {
				StateDto selectedState = (StateDto) parent
						.getItemAtPosition(pos);
				if(selectedState.getDistrictDataAvailable() != null && selectedState.getDistrictDataAvailable()){
					loadDistrictOfStateAsync(userVoterDistrictSpinner,
							userVotingLocationProgressBar,
							userVoterDistrictLinearLayout, selectedState.getId());
				}else{
					userVoterAcLinearLayout.setVisibility(View.GONE);
					userVoterDistrictLinearLayout.setVisibility(View.GONE);
				}
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}

	}

	public class VotingDistrictOnItemSelectedListener implements
			OnItemSelectedListener {
		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			if (pos == 0) {
				userVoterAcLinearLayout.setVisibility(View.GONE);
			} else {
				DistrictDto districtDto = (DistrictDto) parent
						.getItemAtPosition(pos);
				if(districtDto.getAcDataAvailable() != null && districtDto.getAcDataAvailable()){
					loadAcOfDistrictAsync(userVoterAcSpinner,
							userVotingLocationProgressBar,
							userVoterAcLinearLayout, districtDto.getId());
				}else{
					userVoterAcLinearLayout.setVisibility(View.GONE);
				}
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
		}

	}

	private void loadDistrictOfStateAsync(final Spinner districtSpinner,
			final ProgressBar progressBar, final LinearLayout spinnerContainer,
			final long stateId) {
		Log.i("Ravi", "Loading States");
		new AapAsyncTask<String, String, List<DistrictDto>>("District",
				"getdistrictofstate/" + stateId) {
			@Override
			protected void beforeExecute() {
				districtSpinner.setVisibility(View.GONE);
				spinnerContainer.setVisibility(View.GONE);
				progressBar.setVisibility(View.VISIBLE);
			}

			@Override
			protected List<DistrictDto> doInBackground(String... params) {
				try {
					List<DistrictDto> states = DataServices.getInstance()
							.getDistrictsOfStates(stateId);
					Log.i("Ravi", "Loaded Districts");
					return states;
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				return null;
			}

			@Override
			protected void afterExecute(List<DistrictDto> result) {
				progressBar.setVisibility(View.GONE);
				Log.i("Ravi", "Loaded  Districts " + result);
				if (result != null) {
					DistrictDto selecteDistrict = new DistrictDto();
					selecteDistrict.setId(-1L);
					selecteDistrict.setName("--Select District---");
					result = new ArrayList<DistrictDto>(result);
					result.add(0, selecteDistrict);
					districtSpinner.setAdapter(new DistrictSpinnerAdapter(
							UserProfileActivity.this,
							android.R.layout.simple_spinner_item, result));
					districtSpinner.setVisibility(View.VISIBLE);
					spinnerContainer.setVisibility(View.VISIBLE);
					long districtId = -1;
					if(districtSpinner == UserProfileActivity.this.userLivingDistrictSpinner){
						districtId = selectedLivingDistrictId;
					}else{
						districtId = selectedVotingDistrictId;
					}
					
					selectDistrict(districtId, districtSpinner);
				}
			}
		}.execute();

	}

	private void loadAcOfDistrictAsync(final Spinner acSpinner,
			final ProgressBar progressBar, final LinearLayout spinnerContainer,
			final long districtId) {
		Log.i("Ravi", "Loading States");
		new AapAsyncTask<String, String, List<AssemblyConstituencyDto>>(
				"District", "getdistrictofstate/" + districtId) {
			@Override
			protected void beforeExecute() {
				acSpinner.setVisibility(View.GONE);
				spinnerContainer.setVisibility(View.GONE);
				progressBar.setVisibility(View.VISIBLE);
			}

			@Override
			protected List<AssemblyConstituencyDto> doInBackground(
					String... params) {
				try {
					List<AssemblyConstituencyDto> states = DataServices
							.getInstance().getAssemblyConstituencyOfDistrict(
									districtId);
					Log.i("Ravi", "Loaded AC");
					return states;
				} catch (Exception ex) {
					ex.printStackTrace();
				}
				return null;
			}

			@Override
			protected void afterExecute(List<AssemblyConstituencyDto> result) {
				progressBar.setVisibility(View.GONE);
				Log.i("Ravi", "Loaded  AC " + result);
				if (result != null) {
					AssemblyConstituencyDto selecteDistrict = new AssemblyConstituencyDto();
					selecteDistrict.setId(-1L);
					selecteDistrict
							.setName("--Select Assembly Constituency---");
					result = new ArrayList<AssemblyConstituencyDto>(result);
					result.add(0, selecteDistrict);
					acSpinner
							.setAdapter(new AssemblyConstituencySpinnerAdapter(
									UserProfileActivity.this,
									android.R.layout.simple_spinner_item,
									result));
					acSpinner.setVisibility(View.VISIBLE);
					spinnerContainer.setVisibility(View.VISIBLE);
					
					long acId = -1;
					if(acSpinner == UserProfileActivity.this.userLivingAcSpinner){
						acId = selectedLivingAcId;
					}else{
						acId = selectedVotingAcId;
					}
					selectAssemblyContituency(acId, acSpinner);
				}
			}
		}.execute();

	}
}
